/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @param {TreeNode} p
 * @return {TreeNode}
 */
 var inorderSuccessor = function(root, p) {
  let arrive = false;
  function traverse(node) {
      let lr, rr;
      if(node.left) lr = traverse(node.left);
      if(lr) return lr;
      if(arrive) return node;
      if(node.val === p.val) arrive = true;
      if(node.right) rr = traverse(node.right);
      return rr;
  }
  return traverse(root) || null;
};